package com.hvisions.repository;

import com.hvisions.entity.Role;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Author: Lau
 * @Description:
 * @Date: Created in 17:19 2019/11/6
 * @Modified By:
 */
public interface RoleRepository extends JpaRepository<Role,Integer>,JpaSpecificationExecutor<Role> {



    @Query(nativeQuery = true,value = "select r.* from role r\n" +
            "        LEFT JOIN user_role ur\n" +
            "        on r.role_id = ur.role_id\n" +
            "        WHERE ur.user_id = ?1")
    Set<String> findRoleByUserId(String userId);


    List<Role> findAllByNameLike(String name);


    List<Role>  findAllByStatus(Integer status);

    @Modifying
    @Query(nativeQuery = true,value = "UPDATE\n" +
            "        role\n" +
            "        SET\n" +
            "        status=:#{params.status}, update_time=now()\n" +
            "        where\n" +
            "        role_id in (:#{params.roleIds})")
    int updateStatusBatch(Map<String, Object> params);

    @Modifying
    @Query(nativeQuery = true,value = "UPDATE\n" +
            "        role\n" +
            "        SET\n" +
            "        status=?2, update_time=now()\n" +
            "        where\n" +
            "        role_id in (?1)")
    @Transactional//不加事务更新不能成功
    int updateStatusBatch(List<String> roleIds, Integer status);

    @Modifying
    @Query(nativeQuery = true,value = " UPDATE\n" +
            "        role\n" +
            "        SET\n" +
            "        name=:#{params.name},description=:#{params.description}, update_time=now()\n" +
            "        where\n" +
            "        role_id = :#{params.role_id}")
    int updateByRoleId(Map<String, Object> params);
}
